namespace Domotica.Windows.Input
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows.Input;

    public class MultiKeyGesture : KeyGesture
    {
        private int m_checkIndex;
        private KeyGesture[] m_keys;
        private static List<MultiKeyGesture> s_allGestures = new List<MultiKeyGesture>();

        public MultiKeyGesture(KeyGesture[] keys) : base(Key.Oem1, ModifierKeys.None, CreateDisplayStringFromKeyGestures(keys))
        {
            this.m_checkIndex = 0;
            this.m_keys = keys;
            s_allGestures.Add(this);
        }

        public MultiKeyGesture(KeyGesture[] keys, string displayString) : base(Key.Oem1, ModifierKeys.None, displayString)
        {
            this.m_checkIndex = 0;
            this.m_keys = keys;
            s_allGestures.Add(this);
        }

        public static string CreateDisplayStringFromKeyGestures(KeyGesture[] keys)
        {
            StringBuilder displayString = new StringBuilder();
            foreach (KeyGesture key in keys)
            {
                displayString.AppendFormat("{0}, ", key.DisplayString);
            }
            displayString.Remove(displayString.Length - 2, 2);
            return displayString.ToString();
        }

        public override bool Matches(object targetElement, InputEventArgs inputEventArgs)
        {
            if (inputEventArgs is KeyEventArgs)
            {
                KeyEventArgs keyArgs = (KeyEventArgs) inputEventArgs;
                if (keyArgs.IsRepeat)
                {
                    return false;
                }
                if (this.m_keys[this.m_checkIndex].Matches(null, inputEventArgs))
                {
                    this.m_checkIndex++;
                }
                else
                {
                    this.m_checkIndex = 0;
                }
                if (this.m_checkIndex == this.m_keys.Length)
                {
                    this.m_checkIndex = 0;
                    ResetAllGestures();
                    inputEventArgs.Handled = true;
                    return true;
                }
            }
            return false;
        }
        
        public static void ResetAllGestures()
        {
            foreach (MultiKeyGesture gesture in s_allGestures)
            {
                gesture.m_checkIndex = 0;
            }
        }
    }
}

